package cn.wolfcode.luowowo.website.web.controller;

import cn.wolfcode.luowowo.article.domain.*;
import cn.wolfcode.luowowo.article.query.AnswerQuery;
import cn.wolfcode.luowowo.article.query.QuestionsQuery;
import cn.wolfcode.luowowo.article.service.*;
import cn.wolfcode.luowowo.comment.query.AnswerCommentQuery;
import cn.wolfcode.luowowo.comment.service.IAnswerCommentService;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.website.annoation.LoginCheck;
import cn.wolfcode.luowowo.website.annoation.UserParam;
import cn.wolfcode.luowowo.website.web.util.UMEditorUploader;
import cn.wolfcode.luowowo.website.web.util.UploadUtil;
import cn.wolfcoe.luowowo.common.util.baiducheck.SensitiveWordsUtil;
import cn.wolfcoe.luowowo.common.util.AjaxResult;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.qos.common.QosConstants;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("questions")
public class QuestionsController {
    @Reference
    private IQuestionsService questionsService;

    @Reference
    private IDestinationService destinationService;

    @Reference
    private IQuestionsTagService questionsTagService;

    @Reference
    private IAnswerService answerService;

    @Reference
    private IAnswerCommentService answerCommentService;


    @RequestMapping("wenda")
    public String wenda(Model model, @ModelAttribute("qo") QuestionsQuery qo) {
        model.addAttribute("pageInfo", questionsService.query(qo));
        return "questions/wenda";
    }

    @RequestMapping("rank")
    public String rank(Model model, int type) {

        if (type == 1) {
            //查分享数
            model.addAttribute("L", questionsService.viewnumTop());
            return "questions/shareNumTempate";
        } else if (type == 0) {
            //查浏览数
            model.addAttribute("q", questionsService.sharenumTop());
            return "questions/viewnumTemplate";
        } else {
            //回答数
            model.addAttribute("qu", questionsService.thumbsupnumTop());
            return "questions/thumbsupnumTempate";
        }
    }


    //查目的地
    @RequestMapping("public")
    public String bilc(Model model) {
        List<Destination> dests = destinationService.list();
        model.addAttribute("dests", dests);
        return "questions/public";
    }


    //发布问题
    @RequestMapping("save")
    @ResponseBody
    public Object save(@UserParam UserInfo userInfo, Questions questions) {
        if (userInfo == null) {
            AjaxResult result = new AjaxResult(false, "请先登录");
            result.setCode(102);
            return result;
        }
        questions.setUserInfo(userInfo);
        questions.setTitle(SensitiveWordsUtil.SensitiveWordCheck(questions.getTitle()).getContent());
        questions.setContent(SensitiveWordsUtil.SensitiveWordCheck(questions.getContent()).getContent());
        Long id = questionsService.save(questions);
        return AjaxResult.SUCCESS.addData(id);
    }


    @RequestMapping("wendaDetail")
    public String wendaDetail(Model model, @ModelAttribute("qo") AnswerCommentQuery qo, @UserParam UserInfo userInfo, Long id) {
        //根据questionId,来查询当前问题的信息,并且共享过去
        Questions question = questionsService.get(id);
        model.addAttribute("question", question);

       /* //根据questionId,来查询共有多少条回答
        int answersTotal = answerService.countByQuestionId(id);
        model.addAttribute("answerTotal", answersTotal);*/


        qo.setAnswerId(id);
        Page<AnswerComment> page=answerCommentService.query(qo);
        model.addAttribute("page",page);
        return "questions/wendaDetail";
    }








    //保存回答
    @RequestMapping("/saveAnswer")
    @ResponseBody
    @LoginCheck
    public Object saveAnswer(AnswerComment answer, @UserParam UserInfo user, HttpServletResponse response) {
        AjaxResult result = new AjaxResult();
        if (answer.getContent() == null || "".equals(answer.getContent())) {
            return result.mark("内容不能为空");
        }
        answerCommentService.check( answer,user );
        answer.setUserId(user.getId());
        answer.setUsername(user.getNickname());
        answer.setHeadUrl(user.getHeadImgUrl());
        answer.setLevel(user.getLevel());
        answer.setContent(SensitiveWordsUtil.SensitiveWordCheck( answer.getContent()).getContent());
        answer.setCity(user.getCity());
        answer.setCreateTime(new Date());

        result = answerCommentService.saveOrUpdate(answer,user);
        return result;
    }





    @Value("${file.path}")
    private String filePath;

    @RequestMapping("/coverImageUpload")
    @ResponseBody
    public Object coverImageUpload(MultipartFile pic) {
        String upload = UploadUtil.upload(pic, filePath);
        return upload;
    }


    @RequestMapping("/contentImage")
    @ResponseBody
    public String uploadUEImage(MultipartFile upfile, HttpServletRequest request) throws Exception {
        UMEditorUploader up = new UMEditorUploader(request);
        String[] fileType = {".gif", ".png", ".jpg", ".jpeg", ".bmp"};
        up.setAllowFiles(fileType);
        //  up.setMaxSize(10000); //单位KB
        up.upload(upfile, filePath);

        String callback = request.getParameter("callback");
        String result = "{\"name\":\"" + up.getFileName() + "\", \"originalName\": \"" + up.getOriginalName() + "\", \"size\": " + up.getSize()
                + ", \"state\": \"" + up.getState() + "\", \"type\": \"" + up.getType() + "\", \"url\": \"" + up.getUrl() + "\"}";
        result = result.replaceAll("\\\\", "\\\\");
        if (callback == null) {
            return result;
        } else {
            return "<script>" + callback + "(" + result + ")</script>";
        }
    }


}
